package com.hc.appanimal;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.hc.DTO.AnimalDTO;
import com.hc.DTO.MessageDTO;
import com.hc.DTO.TokenDTO;
import com.hc.constants.Constants;
import com.hc.model.utils.MessageModel;
import com.hc.model.utils.TokenModel;
import com.hc.ultil.ImageFilePath;
import com.hc.webservice.InternetUtils;
import com.hc.webservice.ServiceHandlerUpload;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateAnimalActivity extends Activity implements OnClickListener {
	EditText edDescription;
	Button btnAttachImages, btnPublish, btnBack;
	TextView txtTitle, txtAttachImages;
	public static String selectedImagePath = "";
	Dialog dialog;
	AnimationDrawable frameAnimation;
	int count = 0;
	AnimalDTO dto;
	ArrayList<String> arrLinkImg;
	String link;
	ImageView img_view_push_messages, img_new_push_message, contact_us, update;
	private Timer autoUpdate;
	boolean flag = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_update_animal);
		Bundle data = getIntent().getExtras();
		if (data != null) {
			dto = (AnimalDTO) data.getSerializable("images");
		}

		edDescription = (EditText) findViewById(R.id.edDescription);
		btnAttachImages = (Button) findViewById(R.id.btnAttachImages);
		btnPublish = (Button) findViewById(R.id.btnPublish);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnAttachImages.setOnClickListener(this);
		btnPublish.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnBack.setVisibility(View.VISIBLE);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setTextSize(15.0f);
		txtTitle.setText("New Update");
		txtAttachImages = (TextView) findViewById(R.id.txtAttachImages);
		update = (ImageView) findViewById(R.id.update);
		update.setOnClickListener(this);
		img_view_push_messages = (ImageView) findViewById(R.id.img_view_push_messages);
		img_new_push_message = (ImageView) findViewById(R.id.img_new_push_message);
		contact_us = (ImageView) findViewById(R.id.contact_us);

		img_view_push_messages.setOnClickListener(this);
		img_new_push_message.setOnClickListener(this);
		contact_us.setOnClickListener(this);
		arrLinkImg = new ArrayList<String>();

		img_new_push_message
				.setBackgroundResource(R.drawable.new_push_messagef);
		contact_us.setBackgroundResource(R.drawable.contact_us);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		autoUpdate = new Timer();
		autoUpdate.schedule(new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						MessageModel modelMess = MessageModel.getInstance();
						MessageDTO messDTO = modelMess
								.getMessage(UpdateAnimalActivity.this);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd");
						String currentDay = sdf.format(new Date());
						if (messDTO.getDatemessage().equalsIgnoreCase(
								currentDay)) {
							img_view_push_messages
									.setImageResource(R.drawable.view_push_messages_new1);
						}
					}
				});
			}
		}, 0, 5000);
		if(flag){
			ImageLoader.getInstance().clearDiskCache();
			ImageLoader.getInstance()
					.clearMemoryCache();
			flag = false;
		}

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		Bundle data;
		switch (v.getId()) {
		case R.id.btnAttachImages:

			intent = new Intent(Intent.ACTION_PICK);
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					Constants.CAPTURE_RETURN);
			break;
		case R.id.btnPublish:
			if (InternetUtils.getInstance().isConnectingToInternet(
					UpdateAnimalActivity.this)) {
				TokenModel tokenModel = TokenModel.getInstance();
				TokenDTO tokenDTO = tokenModel
						.getToken(UpdateAnimalActivity.this);
				String description = edDescription.getText().toString();
				if (!description.equalsIgnoreCase("") && arrLinkImg.size() > 0) {

					new VerySlowTaskUpload1(arrLinkImg, tokenDTO, description)
							.execute();

				} else if (!description.equalsIgnoreCase("")
						&& arrLinkImg.size() <= 0) {
					new VerySlowTaskUpload(tokenDTO, description).execute();
				} else {
					Toast.makeText(UpdateAnimalActivity.this,
							"Please enter description", Toast.LENGTH_LONG)
							.show();
				}

			} else {
				Toast.makeText(UpdateAnimalActivity.this, "no network",
						Toast.LENGTH_LONG).show();
			}

			break;

		case R.id.btnBack:
			finish();
			break;

		case R.id.img_view_push_messages:
			if (InternetUtils.getInstance().isConnectingToInternet(
					UpdateAnimalActivity.this)) {
				intent = new Intent(UpdateAnimalActivity.this,
						ViewMessageActivity.class);

				startActivity(intent);
				finish();
			} else {
				Toast.makeText(UpdateAnimalActivity.this, "no net work",
						Toast.LENGTH_LONG).show();
			}

			break;

		case R.id.contact_us:
			intent = new Intent(UpdateAnimalActivity.this,
					ContactUsActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.update:
			TokenModel tokenModel = TokenModel.getInstance();
			TokenDTO tokenDTO = tokenModel.getToken(UpdateAnimalActivity.this);
			String dateExpires = tokenDTO.getExpires();
			Date date2 = null;
			Date date1 = null;
			String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
			SimpleDateFormat format = new SimpleDateFormat(pattern,
					Locale.ENGLISH);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String currentDay = sdf.format(new Date());
			String currentDayExpires = format.format(new Date());
			try {
				date1 = format.parse(currentDayExpires);
				date2 = format.parse(dateExpires);
				if (date1.compareTo(date2) < 0) {
					if (InternetUtils.getInstance()
							.isConnectingToInternet(this)) {
						this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								String path = Constants.URL_CATEGORY;
								String[] strs = path.split("/");
								File file = new File(Environment
										.getExternalStorageDirectory()
										+ "/"
										+ Constants.APP_NAME
										+ "/"
										+ strs[4]
										+ "/");
								// deleteDirectory(file);
								DeleteRecursive(file);

							}
						});
						new AsystaskUpdateAnimal(currentDay, tokenDTO,
								UpdateAnimalActivity.this).execute();
						flag = true;
					} else {
						Toast.makeText(UpdateAnimalActivity.this, "no network",
								Toast.LENGTH_LONG).show();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			break;

		default:
			break;
		}

	}
	private void DeleteRecursive(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory())
	        for (File child : fileOrDirectory.listFiles())
	        {
	            child.delete();
	            DeleteRecursive(child);
	        }

	    fileOrDirectory.delete();
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = this.managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constants.CAPTURE_RETURN:
			if (resultCode == Activity.RESULT_OK) {
				if (null == data)
					return;

				String selectedImagePath;
				Uri selectedImageUri = data.getData();

				// MEDIA GALLERY
				selectedImagePath = ImageFilePath.getPath(
						getApplicationContext(), selectedImageUri);

				selectedImagePath.replaceAll("%20", " ");
				selectedImagePath.replaceAll(" ", "");
				Log.i("Image File Path", "" + selectedImagePath);
				// txta.setText("File Path : \n"+selectedImagePath);
				arrLinkImg.add(selectedImagePath);
				// Uri selectedImageUri = data.getData();
				// selectedImagePath = getPath(selectedImageUri);

				String fileName = selectedImagePath.substring(selectedImagePath
						.lastIndexOf('/') + 1);
				;
				if (arrLinkImg.size() > 1) {
					link += "/ " + fileName;
				} else {
					link = fileName;
				}

				txtAttachImages.setText(link);
				// imgAlert.setImageBitmap(decodeFile(selectedImagePath));
			}
			break;

		}
	}

	// public static String getFileNameByUri(Context context, Uri uri) {
	// String fileName = "unknown";// default fileName
	// Uri filePathUri = uri;
	// if (uri.getScheme().toString().compareTo("content") == 0) {
	// Cursor cursor = context.getContentResolver().query(uri, null, null,
	// null, null);
	// if (cursor.moveToFirst()) {
	// int column_index = cursor
	// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);// Instead
	// // of
	// // "MediaStore.Images.Media.DATA"
	// // can
	// // be
	// // used
	// // "_data"
	// filePathUri = Uri.parse(cursor.getString(column_index));
	// fileName = filePathUri.getLastPathSegment().toString();
	// }
	// } else if (uri.getScheme().compareTo("file") == 0) {
	// fileName = filePathUri.getLastPathSegment().toString();
	// } else {
	// fileName = fileName + "_" + filePathUri.getLastPathSegment();
	// }
	// return fileName;
	// }

	public class VerySlowTaskUpload extends AsyncTask<Void, Void, Void> {
		TokenDTO token;
		private int idSysCurrent = 1;
		String description = "";
		boolean flag = false;

		public VerySlowTaskUpload(TokenDTO toke, String _desciption) {
			btnPublish.setVisibility(View.GONE);
			token = toke;
			idSysCurrent = toke.getId();
			description = _desciption;
		}

		@Override
		protected Void doInBackground(Void... params) {
			String strJson = null;
			HttpEntity httpEntity = null;
			HttpClient client = new DefaultHttpClient();
			HttpPost method = new HttpPost(Constants.URL_EX);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());

			List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(
					2);
			postParams.add(new BasicNameValuePair("Desc", description));
			postParams.add(new BasicNameValuePair("CountryCode", "1"));

			UrlEncodedFormEntity formEntity = null;
			try {
				method.setEntity(new UrlEncodedFormEntity(postParams));
				HttpResponse response = client.execute(method);
				httpEntity = response.getEntity();
				strJson = EntityUtils.toString(httpEntity);
				int i = 0;

				if (strJson != null) {
				}
			} catch (Exception e) {
				flag = true;
			}
			String t = strJson;

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (flag) {
				Intent intent = new Intent(UpdateAnimalActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
			} else {
				btnPublish.setVisibility(View.VISIBLE);
				edDescription.setText("");
				Toast.makeText(UpdateAnimalActivity.this,
						"send messages successful", Toast.LENGTH_LONG).show();
			}

		}

	}

	public class VerySlowTaskUpload1 extends AsyncTask<Void, Void, Void> {
		TokenDTO token;
		// String path = "";
		ArrayList<String> arrLink;
		String description;
		boolean flag = false;

		public VerySlowTaskUpload1(ArrayList<String> _arrLink, TokenDTO toke,
				String _description) {
			btnPublish.setVisibility(View.GONE);
			token = toke;
			arrLink = _arrLink;
			description = _description;
			dialog = new Dialog(UpdateAnimalActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			// SendImageHttpPost post = new SendImageHttpPost();
			try {
				ServiceHandlerUpload sv = new ServiceHandlerUpload();
				sv.uploadService(arrLink, token, description);
			} catch (Exception e) {
				flag = true;
			}

			// try {
			// post.sendPost(Constants.URL_EX, path, token.getToken_type(),
			// token.getAccess_token());
			// } catch (ClientProtocolException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// } catch (IOException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// }

			// HttpEntity httpEntity = null;
			// HttpClient client = new DefaultHttpClient();
			// HttpPost method = new HttpPost(Constants.URL_EX);
			// method.setHeader("Content-Type",
			// "application/x-www-form-urlencoded;charset=UTF-8");
			// method.setHeader("Authorization", token.getToken_type() + " "
			// + token.getAccess_token());
			//
			// // List<BasicNameValuePair> postParams = new
			// // ArrayList<BasicNameValuePair>(4);
			// // postParams.add(new BasicNameValuePair("accountType",
			// "GOOGLE"));
			// // postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
			// // postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
			// // postParams.add(new BasicNameValuePair("service", "cl"));
			//
			// UrlEncodedFormEntity formEntity = null;
			// try {
			//
			// HttpResponse response = client.execute(method);
			//
			// httpEntity = response.getEntity();
			// String strJson = EntityUtils.toString(httpEntity);
			// if (strJson != null) {
			// }
			// } catch (Exception e) {
			// // TODO: handle exception
			// }

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();
			if (flag) {
				Intent intent = new Intent(UpdateAnimalActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
			} else {
				btnPublish.setVisibility(View.VISIBLE);
				arrLink = new ArrayList<String>();
				edDescription.setText("");
				txtAttachImages.setText("");
				Toast.makeText(UpdateAnimalActivity.this,
						"Upload messages successful", Toast.LENGTH_LONG).show();
			}

			// Intent intent = new Intent(UpdateAnimalActivity.this,
			// CommunityUpdateActivity.class);
			// Bundle data = new Bundle();
			// data.putString("description",
			// edDescription.getText().toString());
			// data.putInt("numberimg", count);
			// intent.putExtras(data);
			// startActivity(intent);
			// finish();

		}

	}
}
